package com.jyy.prefabricated.service;

import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.dto.CoursePackageDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.BaseStatusEnum;
import com.jyy.prefabricated.enums.CoursePackageTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.vo.CoursePackageData;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class CoursePackageService {

    @Resource
    private CoursePackageMapper coursePackageMapper;

    @Resource
    private CoursePackageContentMapper coursePackageContentMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private ExamPaperMapper paperMapper;

    @Resource
    private QuestionBankMapper questionBankMapper;

    @Resource
    private ExamPaperAreaService areaService;
    @Resource
    private ViewLogMapper viewLogMapper;

    @Resource
    private StudentCoursePackageMapper StudentCoursePackageMapper;

    /**
     * 新增
     *
     * @param dto
     * @return
     */
    public int insert(CoursePackageDto dto) {
        CoursePackage coursePackage = new CoursePackage();
        BeanUtils.copyProperties(dto, coursePackage);
        if (dto.getClassHours() == null) {
            dto.setClassHours(0);
        }
        if (dto.getCoursePackageIds() == null) {
            coursePackage.setRank(1);
        } else {
            int rank = 0;
            for (int i = 0; i < dto.getCoursePackageIds().size(); i++) {
                if (countMaxRank((dto.getCoursePackageIds().get(i))) > rank) {
                    rank = countMaxRank((dto.getCoursePackageIds().get(i)));
                }
            }
            coursePackage.setRank(rank + 1);
        }

//        if (dto.getXiaoeUrl() != null) {
//            int i=dto.getXiaoeUrl().lastIndexOf("/");
//            int j=dto.getXiaoeUrl().lastIndexOf("?");
//            coursePackage.setResourceId(dto.getXiaoeUrl().substring(i+1,j));
//        }
        coursePackage.setStatus(0);
        coursePackageMapper.insert(coursePackage);

        //保存课程包包含的随堂考题目区域
        savePaperId2Area(dto.getAreas(), coursePackage.getId());
        //保存课程包相关课程、题库、考试、练习
        savePackageContent(dto, coursePackage.getId());
        return coursePackage.getId();
    }

    /**
     * 保存试卷id到试卷区域列表
     *
     * @param areas
     * @param id
     */
    private void savePaperId2Area(List<ExamPaperArea> areas, Integer id) {
        if (areas.size() > 0) {
            for (ExamPaperArea area : areas) {
                area.setPaperId(id);
                area.setAreaType(1);
                areaService.update(area);
            }
        }
    }

    /**
     * 获取课程包级别
     *
     * @param id
     * @return
     */
    public int countMaxRank(Integer id) {

        int count = 0;
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(id);
        while (!queue.isEmpty()) {

            Integer p = queue.poll();
            CoursePackageContent coursePackageContent = new CoursePackageContent();
            coursePackageContent.setPackageId(p);
            coursePackageContent.setType(CoursePackageTypeEnum.SEVEN.getValue());
            List<CoursePackageContent> coursePackageContentList = coursePackageContentMapper.selectByParams(coursePackageContent);
            if (coursePackageContentList != null && coursePackageContentList.size() > 0) {
                for (int i = 0; i < coursePackageContentList.size(); i++) {
                    queue.offer(coursePackageContentList.get(i).getId());
                }
            }
            count++;
        }

        return count;
    }

    /**
     * 更新
     *
     * @param dto
     * @return
     */
    public int update(CoursePackageDto dto) {
        if (dto.getId() == null) {
            throw new CustomException("参数id不能为空");
        }

        CoursePackage coursePackage = new CoursePackage();
        BeanUtils.copyProperties(dto, coursePackage);

        coursePackage.setStatus(BaseStatusEnum.VALID.getValue());

        //保存课程包包含的随堂考题目区域
        savePaperId2Area(dto.getAreas(), coursePackage.getId());

        if (dto.getCoursePackageIds() == null) {
            coursePackage.setRank(1);
        } else {
            int rank = 0;
            for (int i = 0; i < dto.getCoursePackageIds().size(); i++) {
                if (countMaxRank((dto.getCoursePackageIds().get(i))) > rank) {
                    rank = countMaxRank((dto.getCoursePackageIds().get(i)));
                }
            }
            coursePackage.setRank(rank + 1);
        }

        int row = coursePackageMapper.updateByPrimaryKeySelective(coursePackage);
        //清空课程包重新保存
        coursePackageContentMapper.deleteByPackageId(dto.getId());
        savePackageContent(dto, dto.getId());

        return row;
    }

    /**
     * 批量修改状态
     *
     * @param dto
     * @return
     */
    public int batchUpdateStatus(BatchDto dto) {
        if (dto.getIds().size() == 0) {
            throw new CustomException("参数id不能为空");
        }
        return coursePackageMapper.batchUpdateStatus(dto.getIds(), dto.getStatus());
    }

    /**
     * 批量删除
     *
     * @param dto
     * @return
     */
    public int batchDelete(BatchDto dto) {
        if (dto.getIds().size() == 0) {
            throw new CustomException("参数id不能为空");
        }
        return coursePackageMapper.batchDelete(dto.getIds());
    }

    /**
     * 保存课程包相关课程
     *
     * @param dto
     */
    private void savePackageContent(CoursePackageDto dto, Integer packageId) {
        List<CoursePackageContent> contents = new ArrayList<>();
        for (Integer courseId : dto.getDocumentCourseIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.DOCUMENT.getValue());
            contents.add(content);
        }
        for (Integer courseId : dto.getRecordingCourseIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.RECORDING.getValue());
            contents.add(content);
        }
        for (Integer courseId : dto.getQuestionBankIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.Four.getValue());
            contents.add(content);
        }
        for (Integer courseId : dto.getExamPaperIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.FIVE.getValue());
            contents.add(content);
        }
        for (Integer courseId : dto.getPracticeIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.SIX.getValue());
            contents.add(content);
        }
        for (Integer courseId : dto.getCoursePackageIds()) {
            CoursePackageContent content = new CoursePackageContent();
            content.setCourseId(courseId);
            content.setPackageId(packageId);
            content.setType(CoursePackageTypeEnum.SEVEN.getValue());
            contents.add(content);
        }
        if (contents != null && contents.size() > 0) {
            coursePackageContentMapper.insert(contents);
        }

    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        return coursePackageMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public CoursePackage selectById(Integer id) {

        return coursePackageMapper.selectByPrimaryKey(id);
    }

    public CoursePackage selectByUserId(Integer id, String userId) throws IOException, NoSuchAlgorithmException {
        CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(id);
        Integer zjNum = 0;
        Integer ygkzj = 0;
        if (userId != null && !"".equals(userId) && coursePackage != null) {
            List<Map> gkjd = new ArrayList<>();
            List<Course> courses = findCourse(coursePackage);
            if (courses != null && courses.size() > 0) {
                for (Course course : courses) {
                    if (course.getFiles() != null) {
                        zjNum += course.getFiles().size();
                        for (CourseFile courseFile : course.getFiles()) {
                            if (courseFile.getPath() != null && !"".equals(courseFile.getPath())) {
                                ViewLog viewLog = new ViewLog();
                                viewLog.setVideoId(courseFile.getPath());
                                viewLog.setSessionId(userId);
                                List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                                if (viewLogList != null && viewLogList.size() > 0) {
                                    if (viewLogList.get(0).getPlayDuration() + 10 >= Integer.valueOf(viewLogList.get(0).getDuration())
                                            && Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) >= Integer.valueOf(viewLogList.get(0).getDuration())) {
                                        Map map = new HashMap();
                                        map.put(courseFile.getPath(), 100);
                                        gkjd.add(map);
                                        ygkzj++;
                                    }

                                }
                            }

                        }
                    }

                }
            }
            coursePackage.setGkjd(gkjd);
        }
        coursePackage.setZjNum(zjNum);
        coursePackage.setYgkzj(ygkzj);
        return coursePackage;
    }

    /**
     * 根据参数查询列表
     *
     * @param courseName 课程包名称
     * @param categoryId 课程包分类id
     * @param status     课程包状态
     * @return
     */
    public List<CoursePackage> selectByParams(String courseName, Integer categoryId, Integer status) {
        return coursePackageMapper.selectByParams(courseName, categoryId, status);
    }

    /**
     * 根据参数查询列表
     *
     * @param courseName  课程包名称
     * @param categoryIds 课程包分类id列表
     * @param status      课程包状态
     * @param sortStatus  排序状态（1、最新、2、最热、3、免费）
     * @return
     */
    public List<CoursePackage> selectDeepByParams(String courseName, Integer plateId, Boolean recommend, List<Integer> categoryIds, Integer status, String orderStr, Integer rank, Integer sortStatus) {
        return coursePackageMapper.selectByParamsDeep(courseName, plateId, recommend, categoryIds, status, orderStr, rank, sortStatus);
    }

    /**
     * 根据分类上下级关系查询分类列表
     *
     * @param categoryId
     * @return
     */
    public List<Integer> selectDeepCategoryIds(Integer categoryId) {
        List<Integer> categoryIds = new ArrayList<>();
        if (categoryId != null) {
            List<CourseCategory> list = courseCategoryService.selectAll();
            List<CourseCategory> categories = courseCategoryService.findCategoryIdByPid(categoryId, list);
            categoryIds.addAll(categories.stream().map(e -> e.getId()).collect(Collectors.toList()));
            categoryIds.add(categoryId);
        }
        return categoryIds;
    }


    /**
     * 根据id查询课程包子集
     *
     * @param pid
     * @return
     */
    public CoursePackage selectTree(Integer pid) {
        CoursePackageContent coursePackageContent = new CoursePackageContent();
        coursePackageContent.setPackageId(pid);
        CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(pid);
        List<CoursePackage> coursePackages = findNext(coursePackageContent);
        coursePackage.setChildren(coursePackages);


        return coursePackage;
    }

    public List<CoursePackage> findNext(CoursePackageContent coursePackageContent) {
        List<CoursePackageContent> coursePackageContentList = coursePackageContentMapper.selectByParams(coursePackageContent);
        if (CollectionUtils.isEmpty(coursePackageContentList)) {
            return null;
        }
        List<CoursePackage> coursePackages = new ArrayList<>();

        for (CoursePackageContent next : coursePackageContentList) {
            CoursePackage result = new CoursePackage();
            if (next.getType().equals(CoursePackageTypeEnum.SEVEN.getValue())) {

                result = coursePackageMapper.selectByPrimaryKey(next.getCourseId());

                CoursePackageContent cp = new CoursePackageContent();
                cp.setPackageId(next.getCourseId());
                List<CoursePackage> nextCoursePackage = this.findNext(cp);

                if (!CollectionUtils.isEmpty(nextCoursePackage)) {
                    result.setChildren(nextCoursePackage);
                }
                coursePackages.add(result);
            }
        }
        return coursePackages;
    }


    /**
     * 根据id查询课程包子集
     *
     * @param pid
     * @return
     */
    public CoursePackageData selectSon(Integer pid) {
        CoursePackageContent coursePackageContent = new CoursePackageContent();
        coursePackageContent.setPackageId(pid);
        CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(pid);
        CoursePackageData result = new CoursePackageData();
        result.setId(coursePackage.getId());
        result.setCourseName(coursePackage.getCourseName());
        result.setTypeName("课程包");

        List<CoursePackageData> coursePackages = findSonNext(coursePackageContent);

        if (coursePackage.getDocumentCourses() != null) {
            for (Course course : coursePackage.getDocumentCourses()) {
                CoursePackageData coursePackageData = new CoursePackageData();
                coursePackageData.setId(course.getId());
                coursePackageData.setCourseName(course.getCourseName());
                coursePackageData.setTypeName("文档课程");
                coursePackages.add(coursePackageData);
            }
        }
        if (coursePackage.getRecordingCourses() != null) {
            for (Course course : coursePackage.getRecordingCourses()) {
                CoursePackageData coursePackageData = new CoursePackageData();
                coursePackageData.setId(course.getId());
                coursePackageData.setCourseName(course.getCourseName());
                coursePackageData.setTypeName("录播课程");
                coursePackages.add(coursePackageData);
            }
        }

        if (coursePackage.getQuestionBanks() != null) {
            for (QuestionBank questionBank : coursePackage.getQuestionBanks()) {
                CoursePackageData coursePackageData = new CoursePackageData();
                coursePackageData.setId(questionBank.getId());
                coursePackageData.setCourseName(questionBank.getName());
                coursePackageData.setTypeName("题库");
                coursePackages.add(coursePackageData);
            }
        }
        if (coursePackage.getExamPapers() != null) {
            for (Exam exam : coursePackage.getExamPapers()) {
                CoursePackageData coursePackageData = new CoursePackageData();
                coursePackageData.setId(exam.getId());
                coursePackageData.setCourseName(exam.getName());
                coursePackageData.setTypeName("考试");
                coursePackages.add(coursePackageData);
            }
        }
        if (coursePackage.getPractices() != null) {
            for (ExamPaper examPaper : coursePackage.getPractices()) {
                CoursePackageData coursePackageData = new CoursePackageData();
                coursePackageData.setId(examPaper.getId());
                coursePackageData.setCourseName(examPaper.getName());
                coursePackageData.setTypeName("练习");
                coursePackages.add(coursePackageData);
            }
        }
        result.setChildren(coursePackages);
        return result;
    }

    public List<CoursePackageData> findSonNext(CoursePackageContent coursePackageContent) {
        List<CoursePackageContent> coursePackageContentList = coursePackageContentMapper.selectByParams(coursePackageContent);
        if (CollectionUtils.isEmpty(coursePackageContentList)) {
            return null;
        }
        List<CoursePackageData> coursePackages = new ArrayList<>();

        for (CoursePackageContent next : coursePackageContentList) {
            CoursePackageData result = new CoursePackageData();
            if (next.getType().equals(CoursePackageTypeEnum.SEVEN.getValue())) {

                CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(next.getCourseId());
                result.setId(coursePackage.getId());
                result.setCourseName(coursePackage.getCourseName());
                result.setRank(coursePackage.getRank());
                List<CoursePackageData> nextCoursePackage = new ArrayList<>();
                if (coursePackage.getDocumentCourses() != null) {
                    for (Course course : coursePackage.getDocumentCourses()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(course.getId());
                        coursePackageData.setCourseName(course.getCourseName());
                        coursePackageData.setTypeName("文档课程");
                        nextCoursePackage.add(coursePackageData);
                    }
                }
                if (coursePackage.getRecordingCourses() != null) {
                    for (Course course : coursePackage.getRecordingCourses()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(course.getId());
                        coursePackageData.setCourseName(course.getCourseName());
                        coursePackageData.setTypeName("录播课程");
                        nextCoursePackage.add(coursePackageData);
                    }
                }

                if (coursePackage.getQuestionBanks() != null) {
                    for (QuestionBank questionBank : coursePackage.getQuestionBanks()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(questionBank.getId());
                        coursePackageData.setCourseName(questionBank.getName());
                        coursePackageData.setTypeName("题库");
                        nextCoursePackage.add(coursePackageData);
                    }
                }
                if (coursePackage.getExamPapers() != null) {
                    for (Exam exam : coursePackage.getExamPapers()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(exam.getId());
                        coursePackageData.setCourseName(exam.getName());
                        coursePackageData.setTypeName("考试");
                        nextCoursePackage.add(coursePackageData);
                    }
                }
                if (coursePackage.getPractices() != null) {
                    for (ExamPaper examPaper : coursePackage.getPractices()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(examPaper.getId());
                        coursePackageData.setCourseName(examPaper.getName());
                        coursePackageData.setTypeName("练习");
                        nextCoursePackage.add(coursePackageData);
                    }
                }
                if (coursePackage.getCoursePackages() != null) {
                    for (CoursePackage cp : coursePackage.getCoursePackages()) {
                        CoursePackageData coursePackageData = new CoursePackageData();
                        coursePackageData.setId(cp.getId());
                        coursePackageData.setCourseName(cp.getCourseName());
                        coursePackageData.setTypeName("课程包");
                        nextCoursePackage.add(coursePackageData);
                    }
                }


                CoursePackageContent cp = new CoursePackageContent();
                cp.setPackageId(next.getCourseId());
                nextCoursePackage.addAll(this.findSonNext(cp));


                if (!CollectionUtils.isEmpty(nextCoursePackage)) {
                    result.setChildren(nextCoursePackage);
                }
                coursePackages.add(result);
            }
        }
        return coursePackages;
    }

    //查找课程包包含的考试集合
    public List<Exam> find(CoursePackage coursePackage) {
        List<Exam> result = new ArrayList<>();
        result.addAll(coursePackage.getExamPapers());
        if (CollectionUtils.isEmpty(coursePackage.getChildren())) {
            return result;
        }
        for (CoursePackage t : coursePackage.getChildren()) {
            result.addAll(t.getExamPapers());
            if (!CollectionUtils.isEmpty(t.getChildren())) {
                result.addAll(find(t));
            }
        }
        return result;
    }

    //查找课程包包含的练习集合
    public List<ExamPaper> findPractices(CoursePackage coursePackage) {
        List<ExamPaper> result = new ArrayList<>();
        result.addAll(coursePackage.getPractices());
        if (CollectionUtils.isEmpty(coursePackage.getChildren())) {
            return result;
        }
        for (CoursePackage t : coursePackage.getChildren()) {
            result.addAll(t.getPractices());
            if (!CollectionUtils.isEmpty(t.getChildren())) {
                result.addAll(findPractices(t));
            }
        }
        return result;
    }

    //查找课程包包含的视频集合
    public List<Course> findCourse(CoursePackage coursePackage) {
        List<Course> result = new ArrayList<>();
        result.addAll(coursePackage.getRecordingCourses());
        if (!CollectionUtils.isEmpty(coursePackage.getCoursePackages())) {
            for (CoursePackage t : coursePackage.getCoursePackages()) {
                result.addAll(t.getRecordingCourses());
                if (!CollectionUtils.isEmpty(t.getCoursePackages())) {
                    result.addAll(findCourse(t));
                }
            }
        }

        return result;
    }

}
